import { Message } from 'element-ui'
import store from '@/store'
import axios from 'axios'
import router from '@/router'
// 设置一个令牌失效时限
const timeOut = 365 * 24 * 60 * 60 * 1000
function isTimeOut() {
  const cur = Date.now()
  const pre = store.state.user.timeStamp
  return cur - pre > timeOut
}
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
}) // 创建一个axios的实例
request.interceptors.request.use(config => {
  // 每次请求前判断令牌是否过期
  if (store.state.user.userToken && isTimeOut()) {
    store.dispatch('user/logout')
    router.push('/login')
    // Message('登录已过期，请重新登录')
    return Promise.reject('token已过期')
  }
  if (store.state.user.userToken) {
    config.headers.Authorization = `Bearer ${store.getters.userToken}`
  }
  return config
}, err => {
  return Promise.reject(err.message)
}) // 请求拦截器

request.interceptors.response.use(response => {
  const { data, message, success } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response?.data?.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
    // Message('登录已过期，请重新登录')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(err)
}
) // 响应拦截器

export default request // 导出axios实例
